/*
 * 代号：凤凰
 * http://www.jphenix.org
 * 2014-06-13
 * V4.0
 */
package com.jphenix.webserver.instancea;

import com.jphenix.standard.docs.ClassInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 2019-09-17 整理了代码格式
 * 
 * @author 刘虻
 * 2006-9-15上午12:20:42
 */
@ClassInfo({"2019-09-17 10:37","KeepAliveCleaner"})
public class KeepAliveCleaner extends Thread {
	
	private int                   timeoutKeepAlive;
	private List<ServeConnection> connections;
	private List<ServeConnection> ingoings;
	private boolean               stopped;

	/**
	 * 构造函数
	 * 2008-7-8下午06:45:15
	 */
	public KeepAliveCleaner() {
		super("KeepAliveCleaner");
		connections = new ArrayList<ServeConnection>();
		ingoings = new ArrayList<ServeConnection>();
		setDaemon(true);
	}

	/**
	 * 母鸡
	 * @author 刘虻
	 * 2008-7-8下午06:45:18
	 * @param conn 母鸡
	 */
	public synchronized void addConnection(ServeConnection conn) {
		synchronized (ingoings) {
			if (stopped == false) {
                ingoings.add(conn);
            }
		}
	}

	/**
	 * 覆盖方法
	 * @author 刘虻
	 * 2008-7-8下午06:45:31
	 * @deprecated
	 */
	@Override
    public void run() {
		long d = getTimeoutKeepAlive();
		while (true) {
			synchronized (ingoings) {
				Iterator<ServeConnection> i = ingoings.iterator();
				while (i.hasNext()) {
					connections.add(i.next());
					i.remove();
				}
			}
			Iterator<ServeConnection> i = connections.iterator();
			long ct = System.currentTimeMillis();
			d = getTimeoutKeepAlive();
			while (i.hasNext()) {
				ServeConnection conn = i.next();
				if (conn.getSocket().isClosed()
						|| (conn.keepAlive == false || (ct - conn.lastWait > d && conn.lastRun < conn.lastWait))
						|| stopped) {
					i.remove();
					try {
						conn.getSocket().close();
					} catch (IOException ioe) {}
				}
			}
			if (stopped && connections.size() == 0) {
                break;
            }
			try {
				sleep(d);
			} catch (InterruptedException ie) {
				stopped = true;
			}
		}
	}
	

	/**
	 * 母鸡
	 * @author 刘虻
	 * 2008-7-8下午06:45:44
	 * @return 母鸡
	 */
	public int getTimeoutKeepAlive() {
		return timeoutKeepAlive;
	}

	/**
	 * 母鸡
	 * @author 刘虻
	 * 2008-7-8下午06:45:53
	 * @param timeoutKeepAlive 母鸡
	 */
	public void setTimeoutKeepAlive(int timeoutKeepAlive) {
		this.timeoutKeepAlive = timeoutKeepAlive;
	}
	
	
}